import React, {Component} from "react";
import Xlsx from 'xlsx'
import ajax from 'ajax'
class ControlledComponents extends Component {
    constructor() {
        super();
        this.state = {
            call: '123456'
        }
    }

    render() {
        return (
            <div>
                <button onClick={this.download}>下载表格</button>

                <form id="uploadForm" encType="multipart/form-data">
                    <input id="file" type="file" name="file"/>
                    <button id="upload" type="button" onClick={this.upload}>upload</button>
                </form>
            </div>
        );
    }

    download = async () => {
        /* 获取 JSON 数据并解析 */
        let url = "https://sheetjs.com/data/executive.json"
        const raw_data = await (await fetch(url)).json()
        /* 总统筛选器 */

        const prez = raw_data.filter(row => row.terms.some(term => term.type === "prez"))
        //展开对象
        const rows = prez.map(row => ({
            name: row.name.first + " " + row.name.last,
            birthday: row.bio.birthday
        }));
        /* 生成工作表和工作簿 */
        const worksheet=Xlsx.utils.json_to_sheet(rows);
        const workbook=Xlsx.utils.book_new();
        Xlsx.utils.book_append_sheet(workbook,worksheet,'Dates')
        /*设置表头*/
        Xlsx.utils.sheet_add_aoa(worksheet,[["姓名","生日"]],{origin:"A1"})
    //    计算列宽
        const max_width=rows.reduce((w,r)=>Math.max(w,r.name.length),100)
        worksheet["!cols"]=[{wch:max_width}];
        /* 创建一个 XLSX 文件并尝试保存到总统.xlsx */
        Xlsx.writeFile(workbook,"总统.xlsx")
    }
    upload=()=>{

        let FromData=new FormData();
        FromData.append('file', document.createElement('#file')[0].files[0])
        document.ajax({
            url: '/upload',
            type: 'POST',
            cache: false,
            data: new FormData(document.createElement('#uploadForm')[0]),
            processData: false,
            contentType: false

        })
    }
}


export default ControlledComponents

